package com.haochang.chunkvod.controller.activity.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseListView;
import com.haochang.base.BaseTextView;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.controller.adapter.order.PackageDetailsAdapter;
import com.haochang.chunkvod.model.order.FoodDetailInfo;
import com.haochang.chunkvod.model.order.FoodInfo;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.model.order.query.GroupGoodsInfo;
import com.haochang.chunkvod.tools.vod.event.EventObserver;
import com.haochang.chunkvod.tools.vod.goods.ShoppingCartManager;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DipPxConversion;
import com.haochang.chunkvod.view.vod.ViewGroup.CustomFlowLayout;
import com.haochang.chunkvod.view.vod.activity.ActivityDialogEnum;
import com.haochang.chunkvod.view.vod.activity.OrderDialogActivity;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

/**
 * @author qintao
 *         created at 2016/6/17 18:25
 *         套餐详情
 */

public class PackageDetailsActivity extends BaseActivity implements EventObserver, CustomFlowLayout.OnSingleCheckedChangeListener_
{
	private TitleView titleView;
	private CustomFlowLayout flowLayout;//中间套餐关联组
	private LinearLayout relationLayout;//相关商品
	private BaseListView listView;
	private PackageDetailsAdapter adapter;
	private BaseTextView tv_foodName;
	private BaseTextView tv_price;
	private ImageView img_cart;
	private BaseTextView tv_estimate;
	private BaseTextView tv_give;
	private RelativeLayout lin_right;
	private List<FoodInfo> foodInfoList = new ArrayList<FoodInfo>();
	private List<GroupGoodsInfo> listPackage;//顶部 商品关联组list
	private OrderData orderData;
	private GoodsInfo goodInfo;

	private boolean isTakeOut;//是否是外带

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		EventProxy.addEventListener(this, IEventConstant.ADD_SHOP_CART_SUCCESS);
	}

	@Override
	public void receiveParam()
	{
		goodInfo = (GoodsInfo) getIntent().getSerializableExtra(IntentKey.GOODSINFO);
		isTakeOut = getIntent().getBooleanExtra(IntentKey.ORDER_TAKEOUT, false);
	}

	@Override
	public void initData()
	{
		orderData = new OrderData(PackageDetailsActivity.this);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_package_details);
		titleView = (TitleView) findViewById(R.id.titleView);
		flowLayout = (CustomFlowLayout) findViewById(R.id.flowLayout);
		relationLayout = (LinearLayout) findViewById(R.id.relationLayout);
		titleView.setTitle(String.format("%s", goodInfo.getGoodsName())).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
			}

			@Override
			public void onDoneClick()
			{
				{
					List<String> list = new ArrayList<String>();
					list.add("退出登录");
					int location[] = new int[2];
					ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
					img.getLocationOnScreen(location);
					int x = location[0];
					final VodPopWindow pop = new VodPopWindow(PackageDetailsActivity.this, list);
					pop.showPopupWindow(titleView, x);
					pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
					{
						@Override
						public void onSelectItem(int position)
						{
							switch (position)
							{
							case 0:
								loginOut();
								break;
							default:
								break;
							}
						}
					});
				}
			}
		});
		tv_foodName = (BaseTextView) findViewById(R.id.tv_foodName);
		tv_price = (BaseTextView) findViewById(R.id.tv_price);
		img_cart = (ImageView) findViewById(R.id.img_cart);
		tv_estimate = (BaseTextView) findViewById(R.id.tv_estimate);
		tv_give = (BaseTextView) findViewById(R.id.tv_give);
		lin_right = (RelativeLayout) findViewById(R.id.lin_right);
		lin_right.setOnClickListener(mOnBaseClickListener);
		listView = (BaseListView) findViewById(R.id.listView);
		tv_foodName.setText(goodInfo.getGoodsName());
		tv_price.setText(String.valueOf(SaleUtils.getSaleString(goodInfo.getPrice()) + "/" + goodInfo.getUnit()));
		adapter = new PackageDetailsAdapter(PackageDetailsActivity.this, R.layout.item_goods_detial, foodInfoList);
		listView.setAdapter(adapter);
		requestGoodsDetailFood(goodInfo.getGoodsId(), goodInfo.getRoomId());
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.lin_right:
				if (!CollectionUtils.isEmpty(foodInfoList))
				{
					Intent intent = new Intent(PackageDetailsActivity.this, OrderDialogActivity.class);
					intent.putExtra(IntentKey.ORDER_TAKEOUT, isTakeOut);
					intent.putExtra(IntentKey.GOODSINFO, goodInfo);
					intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.PACKAGE_TYPE);
					intent.putExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME, "数量");
					intent.setAction("PackageDetailsActivity");
					startActivityForResult(intent, IntentCode.PACKAGE_SELECT_NUM);
				} else
					addSingleGoodsToShopCart();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 添加单品到购物车
	 */
	private void addSingleGoodsToShopCart()
	{
		if (goodInfo.getSurplus() > 0)
		{
			String flavor = goodInfo.getTaste_types();
			String standard = goodInfo.getStandard_types();
			ActivityDialogEnum activityDialogEnum = null;
			JSONArray array = null;
			try
			{
				if (!TextUtils.isEmpty(flavor) && TextUtils.isEmpty(standard))
				{
					activityDialogEnum = ActivityDialogEnum.FLAVOR;
					array = new JSONArray(flavor);
				} else if (TextUtils.isEmpty(flavor) && !TextUtils.isEmpty(standard))
				{
					activityDialogEnum = ActivityDialogEnum.SIZE;
					array = new JSONArray(standard);
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
			if (array != null && array.length() > 0)
			{
				Intent intent = new Intent(PackageDetailsActivity.this, OrderDialogActivity.class);
				intent.putExtra(IntentKey.GOODSINFO, goodInfo);
				intent.putExtra(IntentKey.ORDER_TAKEOUT, isTakeOut);
				intent.putExtra(IntentKey.ACTIVITY_ENUM, activityDialogEnum);
				if (activityDialogEnum == ActivityDialogEnum.SIZE)
					intent.putExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME, "数量");
				intent.setAction("PackageDetailsActivity");
				startActivityForResult(intent, IntentCode.GOODS_ADD_TO_CART_REQUEST);
			} else
			{
				Intent intent = new Intent(PackageDetailsActivity.this, OrderDialogActivity.class);
				intent.putExtra(IntentKey.ORDER_TAKEOUT, isTakeOut);
				intent.putExtra(IntentKey.GOODSINFO, goodInfo);
				intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.DEFAULT);
				intent.putExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME, "数量");
				intent.setAction("PackageDetailsActivity");
				startActivityForResult(intent, IntentCode.GOODS_ADD_TO_CART_REQUEST);
			}
		}
	}

	/**
	 * 获取商品详情
	 */
	private void requestGoodsDetailFood(final String goodsId, String roomId)
	{
		orderData.requestGoodsDetailFood(goodsId, roomId, new OrderData.IOrderGoodDetailListener()
		{
			@Override
			public void onRequestSuccess(GoodsInfo info)
			{
				if (info != null)
				{
					info.setBillId(goodInfo.getBillId());
					info.setIs_give(goodInfo.is_give());
					info.setRoomId(goodInfo.getRoomId());
					goodInfo = info;
					titleView.setTitle(String.format("%s", info.getGoodsName()));
					tv_foodName.setText(info.getGoodsName());
					tv_price.setText(String.valueOf(SaleUtils.getSaleString(info.getPrice()) + "/" + info.getUnit()));
					if (info.getSurplus() > 0)
					{
						if (info.is_give())
						{
							img_cart.setVisibility(View.GONE);
							tv_estimate.setVisibility(View.GONE);
							tv_give.setVisibility(View.VISIBLE);
						} else
						{
							img_cart.setVisibility(View.VISIBLE);
							tv_estimate.setVisibility(View.GONE);
							tv_give.setVisibility(View.GONE);
						}
					} else
					{
						img_cart.setVisibility(View.GONE);
						tv_estimate.setVisibility(View.VISIBLE);
						tv_give.setVisibility(View.GONE);
					}
					if (!CollectionUtils.isEmpty(info.getGroupGoodsInfoList()))
					{
						listPackage = info.getGroupGoodsInfoList();
						initFlowLayout(listPackage);
						relationLayout.setVisibility(View.VISIBLE);
					} else
						relationLayout.setVisibility(View.GONE);
					try
					{
						foodInfoList.clear();
						JSONArray jsonArray = null;
						if (TextUtils.isEmpty(info.getGoodsDetial()))
							jsonArray = new JSONArray();
						else
							jsonArray = new JSONArray(info.getGoodsDetial());
						for (int i = 0; i < jsonArray.length(); i++)
						{
							FoodInfo goodInfo = new FoodInfo(jsonArray.getJSONObject(i));
							foodInfoList.add(goodInfo);
						}
					} catch (JSONException e)
					{
						e.printStackTrace();
					}
					adapter.replaceAll(foodInfoList);
				}
			}
		});
	}

	/**
	 * 初始化 商品关联组view
	 */
	private void initFlowLayout(List<GroupGoodsInfo> list)
	{
		if (!CollectionUtils.isEmpty(list))
		{
			flowLayout.removeAllViews();
			int length = list.size();
			View[] views = new View[length];
			if (length > 0)
			{
				int _10dp = DipPxConversion.dip2px(PackageDetailsActivity.this, 10);
				for (int j = 0; j < length; j++)
				{
					LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					final ViewGroup viewGroup = null;
					RadioButton radioButton = (RadioButton) LayoutInflater.from(PackageDetailsActivity.this).inflate(R.layout.inflate_flowlayot_order_package,
							viewGroup, false);
					params.setMargins(0, 0, _10dp, _10dp);
					radioButton.setLayoutParams(params);
					radioButton.setText(list.get(j).getName());
					if (TextUtils.equals(goodInfo.getGoodsName(), list.get(j).getName()))
					{
						radioButton.setChecked(true);
					} else
					{
						radioButton.setChecked(false);
					}
					views[j] = radioButton;
				}
				flowLayout.addData(views, true);
			}
		}
	}

	/**
	 * 添加套餐到购物车
	 */
	private void addGoodsToShopCart()
	{
		boolean flag = true;
		for (int i = 0; i < foodInfoList.size(); i++)
		{
			FoodInfo foodInfo = foodInfoList.get(i);
			if ((foodInfo.getOrderNum() > 0 ? foodInfo.getOrderNum() : foodInfo.getDefaultNum()) < foodInfo.getQuantity())
			{
				flag = false;
				new VodDialog.Builder(context).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
						.cancelable(true).contentName("还有子餐品可选,确定添加吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
						{
							@Override
							public void onOnlyCancelClick()
							{

							}

							@Override
							public void onOkClick()
							{
								ShoppingCartManager.addPackageDetailToGoods(goodInfo, foodInfoList, true);
							}

							@Override
							public void onCancelClick()
							{

							}
						}).build().show();
				break;
			}
		}
		if (flag)
			ShoppingCartManager.addPackageDetailToGoods(goodInfo, foodInfoList, true);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && requestCode == IntentCode.DOODS_DETIAL_REQUEST && resultCode == RESULT_OK)
		{
			FoodDetailInfo info = (FoodDetailInfo) data.getSerializableExtra(IntentKey.FOODINFO);
			Logger.e(info.getName() + info.getNumber());
			for (int i = 0; i < foodInfoList.size(); i++)
			{
				FoodInfo foodInfo = foodInfoList.get(i);
				if (foodInfo.getCombo_id().equals(info.getCombo_id()))
				{
					List<FoodDetailInfo> list = foodInfo.getFoodList();
					if (CollectionUtils.isEmpty(list))
					{
						return;
					}
					for (int j = 0; j < list.size(); j++)
					{
						FoodDetailInfo detailInfo = list.get(j);
						if (info.getFood_id().equals(detailInfo.getFood_id()))
						{
							detailInfo.setNumber(info.getNumber());
							detailInfo.setFlavor(info.getFlavor());
							break;
						}
					}
					int num = 0;
					for (int j = 0; j < list.size(); j++)
					{
						FoodDetailInfo detailInfo = list.get(j);
						Logger.e(detailInfo.getName() + detailInfo.getNumber());
						num += detailInfo.getNumber();
					}
					foodInfo.setOrderNum(num);
					foodInfo.setDefaultNum(0);
					break;
				}
			}
			adapter.notifyDataSetChanged();
		} else if (requestCode == IntentCode.GOODS_ADD_TO_CART_REQUEST && resultCode == RESULT_OK)
		{
			if (data == null)
			{
				ToastUtils.showText(PackageDetailsActivity.this, "添加成功");
				EventProxy.notifyEvent(IEventConstant.EVENT_SHOP_CART);
			}
		} else if (data != null && requestCode == IntentCode.PACKAGE_SELECT_NUM && resultCode == RESULT_OK)
		{
			goodInfo.setOrderNum(data.getIntExtra(IntentKey.ORDERNUM, 0));
			addGoodsToShopCart();
		}
	}

	@Override
	public void onNotify(Object sender, int eventId, Object... args)
	{
		switch (eventId)
		{
		case IEventConstant.ADD_SHOP_CART_SUCCESS:
			ToastUtils.showText(PackageDetailsActivity.this, "添加成功");
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy()
	{
		EventProxy.removeEventListener(IEventConstant.ADD_SHOP_CART_SUCCESS, this);
		super.onDestroy();
	}

	@Override
	public void onSingleCheckedChanged_(int position, boolean b, CompoundButton compoundButton)
	{
		//选择套餐组之后的操作
		if (null != listPackage && listPackage.size() > 0)
		{
			requestGoodsDetailFood(listPackage.get(position).getGoodsId(), goodInfo.getRoomId());
		}
	}
}
